<?php
namespace App\Repository\Db;

use App\Exceptions\ValidateException;
use App\Repository\Contracts\GoodsInterface;
use App\Repository\Contracts\OrderCartInterface;
use Illuminate\Support\Facades\DB;

/**
 * @Author:: HuangYin
 * @DateTime: 2017-01-16 14:54
 *
 * @Description:
 */
class OrderCartRepository extends Repository implements OrderCartInterface
{
    protected $rules = [
        'created' => [
            'store_id' => 'required',
            'goods_id' => 'required'
        ],
        'updated' => [
            'counts' => 'required|integer'
        ]
    ];

    protected $messages = [
        'store_id.required' => "门店 ID 不能为空",
        'goods_id.required' => "商品 ID 不能为空",
        'counts.required' => "数量不能为空",
        'counts.integer' => "数量必须为整数",
    ];

    protected function modelName()
    {
        return 'App\Model\OrderCart';
    }

    public function lists($storeId)
    {
        return $this->findAll(['store_id' => $storeId])->toArray();
    }

    public function created(array $data)
    {
        $this->validate($data, 'created');
        $cart = $this->model->where('store_id', '=', $data['store_id'])->where('goods_id', '=', $data['goods_id'])->first();
        if ($cart) {
            return $this->increment($cart->id, 'counts', 1);
        }
        $goods = $this->container->make(GoodsInterface::class)->detailBy([['field' => 'goods_id', 'value' => $data['goods_id'], 'operation' => '=']]);
        if ($goods && $goods->status === 1) {
            $data['zh_name'] = $goods->zh_name;
            $data['en_name'] = $goods->en_name;
            $data['price'] = $goods->price;
            $data['counts'] = 1;

            return $this->save($data);
        }

        throw new ValidateException('商品已下架或不存在');
    }

    public function updateCount($id, $counts)
    {
        $this->validate(['counts' => $counts], 'updated');

        return $this->update(['counts' => $counts], $id, 'id');
    }

    public function deleted($ids)
    {
        return $this->delete($ids);
    }

    public function clear()
    {
        return DB::select('delete from `c_order_cart`');
    }
}